package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";
    //⽤用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //⽤用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);


        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLineList)) {
            return pageInfo;
        }
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        Query queryPublish = Query.query(Criteria.where("id").in(ids))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public String savePublish(Publish publish) {
        try {
            if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
                return null;
            }
            publish.setId(ObjectId.get());
            publish.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(publish);

            Album album = new Album();
            album.setCreated(System.currentTimeMillis());
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());
            this.mongoTemplate.save(album, "quanzi_album_" + publish.getId());
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        } catch (Exception e) {
            log.error("发布动态失败~ publish = " + publish, e);
        }
        return publish.getId().toHexString();
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = this.redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }
        List<String> pids = StrUtil.split(data, ',');
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size());
        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) {
            return pageInfo;
        }
        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            return pageInfo;
        }

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }
        boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
        if(!result){
            return false;
        }

        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //⽤用户是否点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }



    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        Boolean result = this.queryUserIsLike(userId, publishId);
        if(!result){
            return false;
        }
        boolean remove = this.removeComment(userId,publishId,CommentType.LIKE);
        if(!remove){
            return false;
        }
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //⽤用户是否点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }



    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        //查询Mongodb
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        //写⼊入Redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey,
                String.valueOf(count));

        return count;
    }



    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);

        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if(ObjectUtil.isNotEmpty(data)){
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("userId").is(userId)
        .and("commentType").is(CommentType.LIKE));
        long count = this.mongoTemplate.count(query, Publish.class);
        if(count == 0){
            return false;
        }
        this.redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        return true;
    }

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId){
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }
    private boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            Comment comment = new Comment();

            comment.setCommentType(commentType.getType());
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            this.mongoTemplate.save(comment);
            Publish publish = this.queryPublishById(publishId);
            //TODO 其他评论对象，暂不不处理理
            comment.setPublishUserId(publish.getUserId());
            return true;
        } catch (Exception e) {
            log.error("保存评论失败",e);
        }
        return false;
    }
    private boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.remove(query,
                Comment.class).getDeletedCount() > 0;
    }

    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("commentType").is(commentType.getType()));
        return this.mongoTemplate.count(query,Comment.class);
    }
}
